package com.liu.susu.thread.task.pool;

import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @FileName ScheduledThreadPoolTest
 * @Description
 * @Author susu
 * @date 2022-03-07
 **/
public class ScheduledThreadPoolTest {
    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);

        System.out.println("当前时间是-->"+LocalDateTime.now());

        //1.schedule--->只延迟执行，且只执行一次（不循环）
//        executorService.schedule(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println(Thread.currentThread().getName()
//                        + "-->" + LocalDateTime.now());
//            }
//        },5,TimeUnit.SECONDS);//推迟5秒执行

        //2.scheduleAtFixedRate 推迟执行(initialDelay=0，不推迟)，然后周期性循环执行task
//        executorService.scheduleAtFixedRate(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println(Thread.currentThread().getName()
//                        + "-->" + LocalDateTime.now());
//                try {
//                    Thread.sleep(5000);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        },5,10,TimeUnit.SECONDS);//推迟5秒执行，然后每10秒执行一次

        //3.scheduleWithFixedDelay 推迟执行(initialDelay=0，不推迟)，然后周期性循环执行task
        executorService.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                System.out.println("ScheduledThreadPoolTest-->"+Thread.currentThread().getName()
                        + "-->" + LocalDateTime.now());
                try {
                    Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },5,10,TimeUnit.SECONDS);

    }

}
